package wsepForum.ui.jaxcent.states;

import java.util.Map;
import java.util.Vector;

import jaxcent.HtmlInputButton;
import jaxcent.HtmlInputPassword;
import jaxcent.HtmlSelect;
import jaxcent.JaxcentObject;
import jaxcent.JaxcentPage;
import jaxcent.Jaxception;
import wsepForum.domain.exceptions.UnAuthorizedException;
import wsepForum.persistance.exceptions.DataBaseIOException;
import wsepForum.persistance.exceptions.WrongUserNameException;
import wsepForum.ui.jaxcent.IXContext;

/**
 * @author Oren
 *
 */
public class XUserEditDetails extends AXUserControl {

	/*****************************
	 * CONSTRUCTOR               *
	 *****************************/
	public XUserEditDetails(IXContext context) {
		super(context);
	}

	/*****************************
	 * METHODS                   *
	 *****************************/
	/* (non-Javadoc)
	 * @see wsepForum.ui.jaxcent.states.XUserEdit#initContent()
	 */
	protected void initContent() {
		super.initContent();
		try {
			JaxcentPage page = this.context.getPage();
    		String userName = this.context.getUserName();
    		HtmlSelect xUserSelect = new HtmlSelect(page,"xseluser");
			// put manageed users in the select control
    		Vector<String> users = this.context.getSession().getHandler().getManagedUsernames();
			String user;
			for (int i=0;i<users.size();i++) {
				user = users.elementAt(i);
				xUserSelect.insertOption(i, user);
				if (user.equals(userName))
					xUserSelect.setSelectedIndex(i);
			}
			dealWithRemove();
    		new HtmlInputPassword(page,"xnewpassword").focus();
		} catch (Jaxception e) {
			this.context.getPage().showMessageDialog("problem with building of the user list.\n" + e);
		}
	}

	/* (non-Javadoc)
	 * @see wsepForum.ui.jaxcent.states.XUserEdit#construct()
	 */
	@Override
	protected void construct() {
		String newPassStr,title,oldPasswordPanel,submitText,userField;
		title = "Edit user details";
		newPassStr = "New Password";
		submitText = "Save";
		oldPasswordPanel =
		"<div id=\"xpanelofold\" class=\"panel\"><div class=\"inner\"><span class=\"corners-top\"><span></span></span>"+
		"<fieldset><dl><dt>"+
		"<label for=\"cur_password\">Current password:</label><br /><span>You must type your current password in order to change details.</span></dt>"+
		"<dd><input tabindex=\"6\" type=\"password\" name=\"xoldpassword\" id=\"xoldpassword\" size=\"30\" value=\"\" class=\"inputbox autowidth\" title=\"Old password\" /></dd>"+
		"</dl></fieldset><span class=\"corners-bottom\"><span></span></span></div>"+
		"</div>";
		userField = "<select tabindex=\"2\" name=\"xseluser\" id=\"xseluser\" >&nbsp;<input tabindex=\"3\" type=\"button\" id=\"xunregister\" value=\"Unregister user\" class=\"button1\" />";
		construct(newPassStr,title,oldPasswordPanel,submitText,userField);
	}

	/* (non-Javadoc)
	 * @see wsepForum.ui.jaxcent.states.XUserEdit#dealWithSubmit(java.util.Map, java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	protected void dealWithSubmit(Map pageData, String newpassword) {
		try {
			String oldpassword = (String) pageData.get("xoldpassword");
			if(!this.context.getSession().getHandler().changePassword(oldpassword, newpassword)) {
				this.context.getPage().showMessageDialog("Changing details failed, check that old password is currect.");
				return;
			}
			this.context.loadSection(0);
		} catch (Exception e) {
			context.getPage().showMessageDialog("Changing details failed, check that old password is currect.");
		}
	}

	/**
	 *
	 */
	private void dealWithRemove() {
		final JaxcentPage page = this.context.getPage();
		new HtmlInputButton(page, "xunregister" ) {
			@SuppressWarnings("unchecked")
			protected void onClick(Map pageData) {
				try {
					try {
						setEnabled(false);
							String user = JaxcentObject.getSelectedValue(pageData.get( "xseluser"));
							if (page.showConfirmDialog("Are you sure you want to unregister "+user+"?")) {
								boolean adminAct = !user.equals(context.getUserName());
								if (context.getSession().getHandler().removeUser(user)) {
									if (adminAct) {
										page.showMessageDialog("User removed succesfully");
										context.loadUserDetails();
									}
								} else {
									page.showMessageDialog("Failed to unregister this user,\nplease chack that you are qualified to do so...");
									setEnabled(true);
								}
							} else {
								setEnabled(true);
							}
						} catch (UnAuthorizedException e) {
							page.showMessageDialog("Failed to unregister this user, you are unauthorized to do so..");
						} catch (WrongUserNameException e) {
							page.showMessageDialog("Failed to unregister this user, user do not exist anymore...");
						} catch (DataBaseIOException e) {
							page.showMessageDialog("Failed to unregister this user,\nsome problem with the database please try again later");
						}
				} catch (Jaxception e) {
					page.showMessageDialog("Failed to read from input fields\n"+e.getMessage());
					context.loadSection(0);
				} catch (Exception e) {
					page.showMessageDialog("Failed to unregister this user,\n"+e.getMessage());
					context.loadSection(0);
				}
	        }
		};
	}
}
